<template>
  <div class="app-container">
    <div class="app-head">
      <el-form>
        <el-row type="flex" justify="space-between">
          <el-col :span="24">
            <el-form-item label="时间" label-width="110px">
              <el-date-picker
                v-model="startDate"
                :picker-options="pickerOptions1"
                :editable="false"
                type="datetime"
                size="medium"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss   "
                placeholder="选择开始时间"
                class="timeLength"
                @change="checkStartTime"
              />
              至
              <el-date-picker
                v-model="endDate"
                :picker-options="pickerOptions2"
                :editable="false"
                type="datetime"
                size="medium"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss   "
                placeholder="选择结束时间"
                class="timeLength"
                @change="checkTime"
              />
            </el-form-item>
          </el-col>
          <el-col>
            <el-button
              v-show="operationManage_search"
              class="btnStyle"
              size="medium"
              type="primary"
              icon="el-icon-search"
              @click="search"
            >查询</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="用户ID" label-width="110px">
              <el-input v-model.trim="userId" size="medium" style="width:199px" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-button
              class="btnStyle"
              size="medium"
              type="primary"
              icon="el-icon-refresh"
              @click="reset"
            >重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="app-btn">
      <el-button
        v-show="operationManage_out"
        type="primary"
        size="medium"
        icon="el-icon-download"
        @click="downLoad"
      >下载</el-button>
    </div>
    <div class="app-table">
      <el-table
        :data="list"
        border
        style="width: 100%"
      >
        <el-table-column label="操作时间">
          <template slot-scope="scope">
            <el-popover
              v-if="scope.row.createtime"
              :content="scope.row.createtime"
              placement="top"
              trigger="hover">
              <span slot="reference" style="cursor:pointer" type="info">{{ scope.row.createtime }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="用户ID">
          <template slot-scope="scope">
            {{ scope.row.userid }}
          </template>
        </el-table-column>
        <el-table-column label="用户名">
          <template slot-scope="scope">
            {{ scope.row.username }}
          </template>
        </el-table-column>
        <el-table-column label="操作类型">
          <template slot-scope="scope">
            {{ scope.row.moduleDesc }}
          </template>
        </el-table-column>
        <el-table-column label="操作详细" width="510">
          <template slot-scope="scope">
            对 <span class="dowhile">{{ scope.row.moduleDesc }}</span> 执行 <span class="dowhile">{{ scope.row.optdesc }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          :current-page="pageid"
          :page-sizes="[10,50,100]"
          :page-size="pagecount"
          :total="count"
          background
          highlight-current-row
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import secret from '@/utils/secret'
import { getList, downLoad } from '@/api/log'
export default {
  name: 'Log',
  data() {
    return {
      list: null,
      date: '', // 日期
      resultDate: '', // 开始时间
      endDate: '', // 结束时间
      startDate: '', // 开始日期
      userId: '', // 用户名ID
      pageid: 1,
      power: null, // 权限
      pagecount: 10,
      downloads: '',
      bbb: '',
      downLoadStart: '',
      downLoadEnd: '',
      count: 0,
      operationManage_out: false, // 导出
      operationManage_search: false, // 查询
      flag: true, // 判断当前显示页数条件
      pickerOptions1: {
        disabledDate(time) {
          // console.log(Date.now())
          return time.getTime() > Date.now()
        }
      },
      pickerOptions2: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      }
    }
  },
  computed: {
    ...mapGetters(['assignment', 'token'])
  },
  mounted() {
    this.search()
    var that = this
    this.assignment.forEach(function(item) {
      if (!!item){ // eslint-disable-line
        if (item.menuCode === 'operationManage') {
          that.power = item.btnList
        }
      }
    })
    this.power.forEach(function(item) {
      if (!!item){ // eslint-disable-line
        if (item.code === 'operationManage_search') {
          that.operationManage_search = true
        }
        if (item.code === 'operationManage_out') {
          that.operationManage_out = true
        }
      }
    })
  },
  methods: {
    // 查询列表
    loadList(starttime, endtime, userId, pageid, pagecount) {
      if (endtime === null) {
        endtime = ''
        this.endDate = ''
      }
      if (starttime === null) {
        starttime = ''
        this.startDate = ''
      }
      const data = {
        // token: this.token,
        starttime: starttime,
        endtime: endtime,
        userid: userId,
        pageid: '1',
        pagecount: pagecount
      }
      console.log('请求参数')
      console.log(data)
      getList(secret.Encrypt(data)).then(response => {
        console.log('返回数据')
        console.log(response)
        if (response.data.list === null) {
          this.count = 0
        } else {
          this.count = parseInt(response.data.count)
        }
        const data = response.data
        this.list = data.list
        this.pageid = 1
      })
    },
    // 搜索
    search() {
      this.loadList(this.startDate, this.endDate, this.userId, 1 + '', this.pagecount + '')
      // 记录查询条件
      this.downLoadStart = this.startDate
      this.downLoadEnd = this.endDate
      this.downloads = this.userId
    },
    // 重置
    reset() {
      this.startDate = ''
      this.endDate = ''
      this.userId = ''
    },
    // 校验结束时间
    checkTime(time) {
      const reg = new RegExp('-', 'g')
      // console.log(newStr)
      var selectTime
      if (!!time) { // eslint-disable-line
        selectTime = new Date(time.replace(reg, '/')).getTime() // 所选时间
      } else {
        selectTime = ''
      }
      const nowTime = Date.now() // 现在的时间
      if (selectTime > nowTime) {
        this.$alert('所选时间不能大于当前时间！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.endDate = ''
          }
        })
      } else {
        if (!!time) {  // eslint-disable-line
          var start
          if (this.startDate !== null) {
            start = new Date(this.startDate.replace(reg, '/')).getTime()
          } else {
            start = ''
          }
          var end = new Date(time.replace(reg, '/')).getTime()
          if (end < start) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'error'
            })
            this.endDate = ''
          }
        }
      }
    },
    // 校验开始时间
    checkStartTime(time) {
      const reg = new RegExp('-', 'g')
      // 比较是否大于现在的时间
      var selectTime
      if (!!time) { // eslint-disable-line
        selectTime = new Date(time.replace(reg, '/')).getTime() // 所选时间
      } else {
        selectTime = ''
      }
      const nowTime = Date.now() // 现在的时间
      if (selectTime > nowTime) {
        this.$alert('所选时间不能大于当前时间！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.startDate = ''
          }
        })
      } else {
        if (!!time) {  // eslint-disable-line
          var end
          if (this.endDate !== null) {
            end = new Date(this.endDate.replace(reg, '/')).getTime()
          } else {
            end = ''
          }
          var first = new Date(time.replace(reg, '/')).getTime()
          if (!!end && first > end) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'error'
            })
            this.startDate = ''
          }
        }
      }
    },
    // 下载
    downLoad() {
      var data = {
        // token: this.token,
        starttime: this.downLoadStart.trim(),
        endtime: this.downLoadEnd.trim(),
        userid: this.downloads
      }
      console.log(data)
      downLoad(secret.Encrypt(data)).then(response => {
        // var blob = new Blob([response], { type: 'application/vnd.ms-excel;charset=UTF-8' })
        // var objectUrl = URL.createObjectURL(blob)
        // window.location.href = objectUrl
        //
        //  let fileName = res.headers['application/vnd.ms-excel;charset=UTF-8'].split('=')[1]
        // // 获取文件名
        // let objectUrl = URL.createObjectURL(new Blob([res.data]))
        // // 文件地址
        // const link = document.createElement('a')
        // link.download = fileName
        // link.href = objectUrl
        // link.click()
        const content = response
        console.log(content)
        const blob = new Blob([content])
        console.log(blob)
        const fileName = '操作日志.xlsx'
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      })
    },
    // 当前条数改变时
    handleSizeChange(num) {
      this.flag = false
      this.pagecount = num
      const data = {
        // token: this.token,
        starttime: this.downLoadStart,
        endtime: this.downLoadEnd,
        userid: this.downloads,
        pageid: 1,
        pagecount: num
      }
      console.log('请求参数')
      console.log(data)
      getList(secret.Encrypt(data)).then(response => {
        this.flag = true
        this.pageid = 1
        this.list = response.data.list // 列表项
        this.count = parseInt(response.data.count) // 总数量
        console.log('返回数据')
        console.log(response)
      }).catch(() => {
        this.$message({
          message: '请求列表失败，请重试',
          type: 'error'
        })
      })
    },
    // 跳转某页
    handleCurrentChange(num) {
      if (this.endDate === null) {
        this.endDate = ''
      }
      if (this.startDate === null) {
        this.startDate = ''
      }
      const data = {
        // token: this.token,
        starttime: this.downLoadStart,
        endtime: this.downLoadEnd,
        userid: this.downloads,
        pageid: num,
        pagecount: this.pagecount
      }
      console.log('请求参数')
      console.log(data)
      // if (this.flag === true) {
      getList(secret.Encrypt(data)).then(response => {
        console.log('返回值')
        console.log(response)
        this.list = response.data.list // 列表项
        this.count = parseInt(response.data.count) // 总数量
        this.pageid = num
      }).catch(() => {
        this.$message({
          message: '请求列表失败，请重试',
          type: 'error'
        })
      })
      // }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .app-btn{
    margin-top: 20px;
    padding: 0 40px;
    margin-bottom: -25px;
    display: flex;
    justify-content: flex-end;
  }
  .timeLength{
    width: 199px !important
  }
  .dowhile{
    font-weight: bold;
  }
  .btnStyle{
    position: absolute;
    right: 20px;
    top: 2px
  }
  .btnStyles{
    position: absolute;
    right: 20px;
    top: 2px
  }
</style>

